//发送文章之前我必要先判断下，输入框是否都选择完毕，如果没有做提示，如果全写则进行提交
//在次请求分类，可以在提交的时候创建一个分类，然后继续进行渲染

import React from 'react';
import './create.css';
import {Card,Input,Select,Tag,Row,Col,Button} from 'antd';
import { SendOutlined } from '@ant-design/icons';
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import { ContentUtils } from 'braft-utils'
import axios from 'axios';
const { Search } = Input;


const myUploadFn = (param) => {
    const serverURL = '/image'
    const xhr = new XMLHttpRequest
    const fd = new FormData()
  
    const successFn = (response) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      
      let data = xhr.responseText;
      var json=JSON.parse(data); 
      param.success({
        url: 'http://10.101.26.125:80/'+json.data
      })
    }
  
    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    }
  
    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.'
      })
    }
  
    xhr.upload.addEventListener("progress", progressFn, false)
    xhr.addEventListener("load", successFn, false)
    xhr.addEventListener("error", errorFn, false)
    xhr.addEventListener("abort", errorFn, false)
  
    fd.append('file', param.file)
    xhr.open('POST', serverURL, true)
    xhr.send(fd)
  
  }

const options = [{ name: 'gold' }, { value: 'lime' }, { value: 'green' }, { value: 'cyan' }];

function tagRender(props) {
  const { label, value, closable, onClose } = props;

return (
    <Tag color={value} closable={closable} onClose={onClose} style={{ marginRight: 3 }}>
      {label}
    </Tag>
  );
}

  export default class Create extends React.Component {
      
      state = {
          title:'',
          catId:'分类',
          content:'',
          current:'',
          editorState: BraftEditor.createEditorState(null),
          options:[],
          article_id:''
      }

      getCategory = () => {
        //查到分类的标签
        axios.get('/categories').then((res)=>{
            let result = res.data.data.map((item)=>{
                console.log(item);
                return {
                    value:item['name'],
                    cateid:item['id']
                }
            })
            this.setState({
                options:result,
            })
        })
      }

      componentDidMount(){
        this.getCategory()

        //调用接口进行传值
        //进行一个判断因为正常进入的时候编辑窗口，没有赋值，但是当我们进行编辑的时候应该要将原来的值进行渲染
        let url = window.location.href.split('/')[4]
        if(parseInt(url)){
            //通过接口进行取值
            axios.get('/articles/get',{
                params: {
                    "article_id":parseInt(url)
                }
            }).then(res=>{
                if(res.data.data){
                    this.setState({
                        editorState: ContentUtils.insertHTML(this.state.editorState,res.data.data['article']['content']),
                        title:res.data.data['article']['title'],
                        catId:res.data.data['article']['category'],
                        article_id:parseInt(url)
                    })
                }else{
                    window.location.reload()
                }
            })
        }
        
      }

        InputVal = (e) =>{
            this.setState({
                title:e.target.value
            })
        }

        handleChange = (editorState) => {
            this.setState({ editorState })
            
        }
        
        commit = () => {
            //将文章的内容发送到服务器上进行保存
            let data = {
                "title":this.state.title,
                "content":this.state.editorState.toHTML(),
                "category_name":this.state.catId,
                "article_id":this.state.article_id
            }
            console.log(data);
            axios.post('/articles/create',data).then((res)=>{
                res.status == '200' ? this.props.history.push('/manage') : alert('上传失败')
            })  
        }

        selectCat = (value) => {
            this.setState({catId:value})
        }

        

        render(){
        let sea = (
            <div>
                <Row>
                    <Col span={12}>
                        <Input value={this.state.title} onChange={this.InputVal} size="large" placeholder="请输入文章标题..." prefix={<SendOutlined />} />
                    </Col>
                    <Col span={2}></Col>
                    <Col span={6}>
                        <Select
                            defaultActiveFirstOption
                            value={this.state.catId}
                            onChange={this.selectCat}
                            size='large'
                            showArrow
                            tagRender={tagRender}
                            defaultValue={['分类']}
                            style={{width:'100px'}}
                            options={this.state.options}
                        />
                    </Col>
                    <Col span={4}>
                    <Button onClick={this.commit} type="primary" icon={<SendOutlined  />} size='large'>
                        发布
                    </Button>
                    </Col>
                </Row>   
            </div>
        )
          return (
            <Card title={sea}  bordered={false} >
                 <BraftEditor value={this.state.editorState} onChange={this.handleChange}  className='create-header' media={{uploadFn: myUploadFn}}/>
            </Card>
          )
          
          
         
      }
  }







